package linlin;

import java.util.Arrays;

/**
 * Created by lingfengsan on 2018/9/15.
 *
 * @author lingfengsan
 */
class ListNode {
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}

public class ArrToListNode {
    public static ListNode arrToListNode(int[] arr) {
        ListNode pNode = new ListNode(-1);
        ListNode head = pNode;
        for (int i = 0; i < arr.length; i++) {
            ListNode node = new ListNode(arr[i]);
            pNode.next = node;
            pNode = node;
        }
        return head.next;
    }

    public static void ListNodeToarr(ListNode node) {
        if (node == null)
            return;
        ListNode pNode = node;
        int n = 10;
        int[] arr = new int[n];
        int i = 0;
        while (pNode.next != null) {
            arr[i++] = pNode.val;
            pNode = pNode.next;
        }
        System.out.println(Arrays.toString(arr));
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        //数组-》链表
        ListNode node = arrToListNode(arr);//1-2-3-4-5
        //链表反转
        ListNode temp = ReverseList(node);
        ListNodeToarr(temp);//5-4-3-2-1
        //链表-》数组
        for (int ar : arr) {
            System.out.print(ar + ",");
        }
    }


    public static ListNode ReverseList(ListNode head) {
        if (head == null)
            return null;
        ListNode pre = null;
        ListNode next = null;
        ListNode cur = head;
        //pre, head, next
        while (cur != null) {
            next = cur.next;
            cur.next = pre;

            pre = cur;
            cur = next;
        }
        return pre;
    }
}
